package cn.zjw.demo.grpc;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

@Slf4j
public class SpeechRecognizerClientPool {
    private static GenericObjectPool<SpeechRecognizerClient> speechRecognizerClientPool;

    private SpeechRecognizerClientPool() {
    }

    private static GenericObjectPool<SpeechRecognizerClient> getObjectPool() {
        if (speechRecognizerClientPool == null) {
            synchronized (SpeechRecognizerClientPool.class) {
                if (speechRecognizerClientPool == null) {
                    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
                    /** 下面的配置均为默认配置,默认配置的参数可以在BaseObjectPoolConfig中找到 */
                    poolConfig.setMaxTotal(8); // 池中的最大连接数
                    poolConfig.setMinIdle(2); // 最少的空闲连接数
                    poolConfig.setMaxIdle(8); // 最多的空闲连接数
                    poolConfig.setMaxWaitMillis(-1); // 当连接池资源耗尽时,调用者最大阻塞的时间,超时时抛出异常 单位:毫秒数
                    poolConfig.setLifo(true); // 连接池存放池化对象方式,true放在空闲队列最前面,false放在空闲队列最后
                    poolConfig.setMinEvictableIdleTimeMillis(1000L * 60L * 30L); // 连接空闲的最小时间,达到此值后空闲连接可能会被移除,默认即为30分钟
                    poolConfig.setBlockWhenExhausted(true); // 连接耗尽时是否阻塞,默认为true
                    /** 连接池创建 */
                    speechRecognizerClientPool = new GenericObjectPool<>(new SpeechRecognizerClientFactory(), poolConfig);

                }
            }
        }
        return speechRecognizerClientPool;
    }

    /**
     * 从连接池中获取一个客户端
     *
     * @return
     */
    public static SpeechRecognizerClient borrowObject() {
        SpeechRecognizerClient client = null;
        try {
            client = getObjectPool().borrowObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 返还对象
     *
     * @param client 将client返回给连接池
     */
    public static void returnObject(SpeechRecognizerClient client) {
        getObjectPool().returnObject(client);
    }
}
